package com.anxin.act.task.service;

import com.alibaba.fastjson.JSONObject;
import com.anxin.act.task.dao.ViewHiTaskDao;
import com.anxin.act.task.dao.ViewRuTaskDao;
import com.anxin.act.task.dao.WfPushLogDao;
import com.anxin.act.task.entity.ViewHiTask;
import com.anxin.act.task.entity.ViewRuTask;
import com.anxin.act.task.entity.WfPushLog;
import com.anxin.act.task.vo.TaskVo;
import com.anxin.act.utils.ActTaskUtils;
import com.anxin.common.utils.LogUtils;
import com.anxin.common.utils.sys.UserUtils;
import com.anxin.framework.redis.RedisMq;
import com.anxin.framework.security.entity.SysTempToken;
import com.anxin.sys.system.entity.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 待办对接
 */
@Service
@Transactional(readOnly = false)
public class ActDockingDelTaskService implements RedisMq {

    @Autowired
    private WfPushLogService wfPushLogService;

    @Autowired
    private ViewHiTaskDao viewHiTaskDao;

    @Autowired
    private WfPushLogDao wfPushLogDao;

    @Autowired
    private ActDockingSendService actDockingSendService;



    @Override
    public boolean onMessage(String message) {
        JSONObject dataJson = JSONObject.parseObject(message);
        String taskId = dataJson.getString("taskId");
        String actId = dataJson.getString("actId");
        String assignee = dataJson.getString("assignee");

        List<WfPushLog> wfPushLogList = wfPushLogService.findListByTaskId(taskId,"TODO");
        for (WfPushLog wfPushLog : wfPushLogList) {
            SysUser user = UserUtils.getUser(wfPushLog.getActAssignee());
            if (assignee.equals(user.getUserName())){
                this.delTask(taskId,wfPushLog.getActAssignee());
            }else {
                this.delTodoTask(actId,taskId,user);
            }
        }

        return true;
    }

    /**
     * 删除待办信息
     * @param taskId 任务ID
     * @param userId 用户Id
     */
    @Transactional(readOnly = false)
    public void delTask(String taskId,String userId){
        SysUser user = UserUtils.getUser(userId);

        ViewHiTask viewHiTask = viewHiTaskDao.getById(taskId);

        // 删除待办发送记录
        this.delTodoTask(viewHiTask.getActId(),viewHiTask.getId(),user);

        // 保存已办推送记录
        wfPushLogService.sendHiTask(viewHiTask,userId,"SUCCESS",null);
        // 推送已办
        actDockingSendService.sendHiTask(viewHiTask,user.getId(),user.getUserName());
    }


    /**
     * 删除之前推送的待办
     * @param actId 流程实例ID
     * @param taskId 任务ID
     * @param user 审批人
     */
    public void delTodoTask(String actId,String taskId,SysUser user){

        // 删除待办发送记录
        wfPushLogDao.deleteByTaskId(taskId,user.getId());

        // 删除待办
        actDockingSendService.delTodoTask(actId,taskId,user.getId(),user.getUserName());
    }
}
